from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.database import get_db
import app.schemas as schemas
from app.repositories.scan_path_repository import ScanPathRepository

router = APIRouter()

@router.get("/", response_model=List[schemas.ScanPath])
async def get_scan_paths(db: Session = Depends(get_db)):
    """获取所有扫描路径"""
    try:
        print("正在获取扫描路径...")
        repo = ScanPathRepository()
        paths = await repo.get_scan_paths(db)
        print(f"获取到 {len(paths)} 个扫描路径")
        return paths
    except Exception as e:
        print(f"获取扫描路径时出错: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/", response_model=schemas.ScanPath)
async def create_scan_path(path: schemas.ScanPathCreate, db: Session = Depends(get_db)):
    """添加新的扫描路径"""
    repo = ScanPathRepository()
    try:
        return await repo.create_scan_path(db, path)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.put("/{path_id}", response_model=schemas.ScanPath)
async def update_scan_path(path_id: int, path: schemas.ScanPathCreate, db: Session = Depends(get_db)):
    """更新扫描路径"""
    repo = ScanPathRepository()
    updated_path = await repo.update_scan_path(db, path_id, path)
    if not updated_path:
        raise HTTPException(status_code=404, detail="扫描路径不存在")
    return updated_path

@router.delete("/{path_id}")
async def delete_scan_path(path_id: int, db: Session = Depends(get_db)):
    """删除扫描路径"""
    repo = ScanPathRepository()
    success = await repo.delete_scan_path(db, path_id)
    if not success:
        raise HTTPException(status_code=404, detail="扫描路径不存在")
    return {"success": True}
